﻿CREATE FUNCTION [dbo].[RATE_Payment](
	@AF float,@IR float,@Term smallint,@OpenDate smalldatetime,@FstDueDate smalldatetime,@PmtsPerYear tinyint,@BaseDays smallint
)RETURNS numeric(18,2) AS
BEGIN

--IF @IR < 0 SET @IR = 0
IF @IR >=  1 SET @IR = @IR/100.0
IF @IR <= -1 SET @IR = @IR/100.0

DECLARE @SP int SET @SP = @BaseDays/@PmtsPerYear --Standard Period
DECLARE @DTF int/*Days to First Pmt*/SET @DTF = DATEDIFF(dd,@OpenDate,@FstDueDate)
IF @DTF < 0 SET @DTF = 1
DECLARE @FNP float/*No Periods to First Pmt*/SET @FNP = @DTF/@SP
DECLARE @FND  float/*No Odd Days to First Pmt*/SET @FND = @DTF-@FNP*@SP
DECLARE @ODF  float/*Odd Days Factor*/SET @ODF = @FND/@SP
DECLARE @PR float/*Periodic Rate*/SET @PR = @IR/@PmtsPerYear
DECLARE @INT float/*Finance Charge*/SET @INT = @AF*@PR*(@Term+(@FNP-1)+@ODF)
DECLARE @PMT numeric(18,2)/*Payment*/SET @PMT = FLOOR((@AF+@INT)/@Term*100.0)/100.0
RETURN @PMT
END
